package com.example.Arithmetic.Lettcode;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * 日期：2024/1/3
 * 时间：9:37
 * 描述：全排列，计算几个数字能组成的不同字符串，去除相同字符串
 * 回溯思想，进去是一个状态，回来把状态重置
 */
public class E01Lettcode47 {
    public static List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> list = new LinkedList<>();
        Arrays.sort(nums);
        rec(nums, new boolean[nums.length], new LinkedList<>(), list);
        return list;
    }

    private static void rec(int[] nums, boolean[] booleans, LinkedList<Integer> stack, List<List<Integer>> list) {
        if (stack.size() == nums.length) {
            list.add(new ArrayList<>(stack));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
//            判断上一个索引状态和是否相等
            if (i > 0 && nums[i] == nums[i - 1] && !booleans[i - 1]) {
                continue;
            }
            if (!booleans[i]) {
                booleans[i] = true;
                stack.push(nums[i]);
                rec(nums, booleans, stack, list);
                booleans[i] = false;
                stack.pop();
            }
        }
    }

    @Test
    public void main() {
        List<List<Integer>> permute = permute(new int[]{1, 1, 3,1});
        for (List<Integer> s : permute) {
            System.out.println(s);
        }
    }
}

